package com.lzx.adx.report.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lzs.adx.commmon.service.impl.CrudServiceImpl;
import com.lzs.adx.commmon.utils.ConvertUtils;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.dao.ReportDao;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.WphOrderDTO;
import com.lzx.adx.report.entity.ReportEntity;
import com.lzx.adx.report.service.BackDataService;
import com.lzx.adx.report.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReportServiceImpl extends CrudServiceImpl<ReportDao, ReportEntity, ReportDTO> implements ReportService {

    @Autowired
    private ReportMapper reportMapper;



    @Autowired
    private BackDataService backDataService;

    @Override
    public QueryWrapper<ReportEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String bizRequestId = (String)params.get("bizRequestId");
        String ordertime = (String)params.get("ordertime");
        String dspId = (String)params.get("dsp_id");

        QueryWrapper<ReportEntity> wrapper = new QueryWrapper<>();

        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(dspId), "dsp_id", dspId);
        wrapper.eq(StringUtils.isNotBlank(bizRequestId), "biz_request_id", bizRequestId);
        wrapper.eq(StringUtils.isNotBlank(ordertime), "day_time", ordertime);
        wrapper.isNull(null != params.get("resultType"), "result_type");
        wrapper.last(null != params.get("limit"), "limit 1");
        wrapper.orderByDesc("day_time");
        return wrapper;
    }

    @Override
    public List<ReportDTO> list(Map<String, Object> params) {
        List<ReportDTO> list = super.list(params);
//        if(CollectionUtil.isEmpty(list)){
//            if(params.containsKey("bizRequestId")) {
//                String bizRequestId = params.get("bizRequestId").toString();
//                Query query = new Query(Criteria.where("bizRequestId").is(bizRequestId));
//                List<ReportDTO> reportDTOS = mongoTemplate.find(query, ReportDTO.class);
//                if(CollectionUtil.isNotEmpty(reportDTOS)){
//                    //数据库查询不到去mongodb里面查询
//                    log.info("命中mongodb的查询----请求ID{}",bizRequestId);
//                    return reportDTOS;
//                }
//            }
//        }
        return list;
    }

    @Override
    public void saveData(ReportDTO dto) {
        ReportEntity report=  reportMapper.toReport(dto);
        report.setDay(DateUtil.format(new Date(),createFormatter("yyyy-MM-dd")));
        report.setDayTime(DateUtil.format(new Date(),createFormatter("yyyyMMddHH")));


        this.baseDao.insert(report);
        dto.setId(report.getId());

        //存储一份到mongodb
//        mongoTemplate.save(dto);

    }

    @Override
    public ReportDTO getNewData(String id, String orderTime, WphOrderDTO wphOrderDTO) {
        if(StringUtils.isBlank(wphOrderDTO.getStatParam())){
            ReportDTO reportDTO = dateBack(id, wphOrderDTO);
            if (reportDTO != null) return reportDTO;
        }else {
            LambdaQueryWrapper<ReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ReportEntity::getDspId, id);
            lambdaQueryWrapper.eq(ReportEntity::getIp, wphOrderDTO.getStatParam());
            lambdaQueryWrapper.last("limit " + 200);

            List<ReportEntity> reportEntities = this.baseDao.selectList(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(reportEntities)) {
                log.info("通过IP归因归因，订单号{}", wphOrderDTO.getOrderSn());
                List<ReportEntity> collect = reportEntities.stream().filter(t -> StringUtils.isBlank(t.getResultType())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    ReportEntity reportEntity = collect.get(0);
                    ReportDTO reportDTO = new ReportDTO();
                    BeanUtils.copyProperties(reportEntity, reportDTO);
                    return reportDTO;
                }
            } else {
                ReportDTO reportDTO = dateBack(id, wphOrderDTO);
                if (reportDTO != null) return reportDTO;

            }
          
        }

        return null;
    }

    @Nullable
    private ReportDTO dateBack(String id, WphOrderDTO wphOrderDTO) {
        log.info("通过时间归因，订单号{}", wphOrderDTO.getOrderSn());
        //如果当天的找不到，在向前查询一天
        LambdaQueryWrapper<ReportEntity> lambdaQueryWrapperss = new LambdaQueryWrapper<>();
        lambdaQueryWrapperss.eq(ReportEntity::getDspId, id);
        lambdaQueryWrapperss.orderByDesc(ReportEntity::getDayTime);
        lambdaQueryWrapperss.last("limit " + 200);
        List<ReportEntity> reportEntitiesss = this.baseDao.selectList(lambdaQueryWrapperss);
        if (CollectionUtil.isNotEmpty(reportEntitiesss)) {
            List<ReportEntity> collect = reportEntitiesss.stream().filter(t -> StringUtils.isBlank(t.getResultType())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(collect)) {
                ReportEntity reportEntity = collect.get(0);
                ReportDTO reportDTO = new ReportDTO();
                BeanUtils.copyProperties(reportEntity, reportDTO);
                return reportDTO;
            }
        }
        return null;
    }

    @Override
    public ReportDTO getNewData(String id, String orderTime) {
        LambdaQueryWrapper<ReportEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReportEntity::getDspId,id);
        lambdaQueryWrapper.orderByDesc(ReportEntity::getDayTime);
        lambdaQueryWrapper.last("limit "+200);

        List<ReportEntity> reportEntities = this.baseDao.selectList(lambdaQueryWrapper);
        if(CollectionUtil.isNotEmpty(reportEntities)) {
            List<ReportEntity> collect = reportEntities.stream().filter(t -> StringUtils.isBlank(t.getResultType())).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(collect)){
                ReportEntity reportEntity = collect.get(0);
                ReportDTO reportDTO = new ReportDTO();
                BeanUtils.copyProperties(reportEntity, reportDTO);
                return reportDTO;
            }
        }else{
            //如果当天的找不到，在向前查询一天

        }
        return  null;
    }

    @Override
    public ReportDTO getReportData(String id, String dapId) {
        LambdaQueryWrapper<ReportEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReportEntity::getDspId, dapId);
        lambdaQueryWrapper.eq(ReportEntity::getRequestId, id);
        lambdaQueryWrapper.last("limit 1");
        ReportEntity reportEntity = this.baseDao.selectOne(lambdaQueryWrapper);
        if (null != reportEntity) {
            ReportDTO reportDTO = new ReportDTO();
            BeanUtils.copyProperties(reportEntity, reportDTO);
            return reportDTO;
        }
        return null;
    }
    @Override
    public void updateData(ReportDTO reportDTO,String eventType) {
        super.update(reportDTO);

        //1.存储回传数据

        backDataService.saveData(reportDTO,eventType);

        //更新mongodb内容
//        mongoTemplate.save(reportDTO);
    }

    @Override
    public void updateData(ReportDTO reportDTO, String eventType, Integer type) {
        super.update(reportDTO);

        //1.存储回传数据
        backDataService.saveData(reportDTO,eventType,type);
    }

    public static DateTimeFormatter createFormatter(String pattern) {
        return DateTimeFormatter.ofPattern(pattern, Locale.getDefault())
                .withZone(ZoneId.systemDefault());
    }



}